package com.jdew.thkj.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jdew.thkj.R;
import com.jdew.thkj.adapter.FreeAdapter;
import com.jdew.thkj.adapter.FreeZRAdapter;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.FreeBean;
import com.jdew.thkj.bean.ZeroBuyBean;
import com.jdew.thkj.dialog.CommonDialog;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.OnItemClickListener;
import com.jdew.thkj.utils.GroupItem;
import com.jdew.thkj.utils.GroupItemDecoration;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class NewrEcruitsExclusiveActivity extends BaseActivity {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.to_submit)
    TextView toSubmit;
    @Bind(R.id.rules)
    RelativeLayout rules;
    @Bind(R.id.smartRefresh)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.recyclerview)
    RecyclerView recyclerview;
    private List<FreeBean> list = new ArrayList<>();
    private List<FreeBean> datalist = new ArrayList<>();
    private FreeAdapter adapter;
    private View groupView;
    private long startTime = 0;
    private long endTime = 0;

    @Override
    public int bindLayout() {
        return R.layout.activity_newr_ecruits;
    }

    @Override
    public void initView(View view) {
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        adapter = new FreeAdapter(this, datalist);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        rules.setOnClickListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(this));
        setRcycleview(recyclerview, adapter);
        initRefresh();
        RequestData();
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        toSubmit.setOnTouchListener(shopCarSettleTouch);
        groupView = layoutInflater.inflate(R.layout.item_group, null);
        recyclerview.addItemDecoration(new GroupItemDecoration(this, groupView, new GroupItemDecoration.DecorationCallback() {
            @Override
            public void setGroup(List<GroupItem> groupList) {
                GroupItem groupItem;
                if(list.size()>0){
                    groupItem = new GroupItem(0);
                    groupItem.setData("name", "———今日0元购———");
                    groupList.add(groupItem);
                }
                groupItem = new GroupItem(list.size());
                groupItem.setData("name", "———历史0元购———");
                groupList.add(groupItem);
            }

            @Override
            public void buildGroupView(View groupView, GroupItem groupItem) {
                TextView textName = (TextView) groupView.findViewById(R.id.free);
                textName.setText(groupItem.getData("name").toString());
            }
        }));
        adapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                String aliAccount = sp.getString("AliAccount", "");
                if (position >= list.size()) {
                    ToastUtils.getInstance(NewrEcruitsExclusiveActivity.this).showMessage("该活动已到期！");
                    return;
                }
                if ("".equals(aliAccount)) {
                    commomDialog("请绑定支付宝!");
                    return;
                }
                if (datalist.get(position).getIsDelete().equals("1")) {
                    ToastUtils.getInstance(NewrEcruitsExclusiveActivity.this).showMessage("该商品已被抢光！");
                    return;
                }
                String itemId = datalist.get(position).getShopId();
                toDetail(itemId);
            }
        });
        changeStatusBarTextColor();
        title.setText("新人专享");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.rules: {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                Intent in = new Intent(this, CommonWebView.class);
                in.putExtra("url", "http://www.taohuikeji.com/md.html");
                in.putExtra("title", "活动规则");
                startActivity(in);
            }
            break;
            default:
                break;
        }
    }

    private void initRefresh() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                RequestData();
                refreshLayout.finishRefresh();
            }
        });
    }

    private void changeStatusBarTextColor() {
        if (Build.VERSION.SDK_INT >= 21) {
            Window window = this.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.color_ffffff));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//设置状态栏黑色字体
        }
    }

    public void RequestData() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetFreeList(RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<ZeroBuyBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(ZeroBuyBean bean) {
                datalist.clear();
                list.clear();
                adapter.setDataList(datalist);
                if (bean.getCode().equals("0")) {
                    list.addAll(bean.getData().getDatajr());
                    datalist.addAll(list);
                    datalist.addAll(bean.getData().getDatazr());
                    adapter.setDataList(datalist);
                }
            }
        });
    }

    public void toDetail(String itemId) {
        Bundle b = new Bundle();
        b.putSerializable("itemId", itemId);
        b.putSerializable("phone", "15325799911");
        startActivity(ZeroTbProductDetailActivity.class, b);
    }

    public void commomDialog(String Message) {
        new CommonDialog.Builder(this)
                .setTitle("提示")
                .setMessage(Message)
                .setMessageGravity()
                .setCanceledOnTouchOutside(false)
                .setPositiveButton("我知道了", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(BindZhifuBaoActivity.class);
                    }
                }).show();
    }

    private View.OnTouchListener shopCarSettleTouch = new View.OnTouchListener() {
        int lastX, lastY;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int ea = event.getAction();
            toSubmit.setAlpha(0.5f);
            DisplayMetrics dm = getResources().getDisplayMetrics();
            int screenWidth = dm.widthPixels;
//            int screenHeight = dm.heightPixels - 100;//需要减掉图片的高度
            int screenHeight = dm.heightPixels;//需要减掉图片的高度
            switch (ea) {
                case MotionEvent.ACTION_DOWN:
                    lastX = (int) event.getRawX();//获取触摸事件触摸位置的原始X坐标
                    lastY = (int) event.getRawY();
                    startTime = System.currentTimeMillis();
                case MotionEvent.ACTION_MOVE:
                    //event.getRawX();获得移动的位置
                    int dx = (int) event.getRawX() - lastX;
                    int dy = (int) event.getRawY() - lastY;
                    int l = v.getLeft() + dx;
                    int b = v.getBottom() + dy;
                    int r = v.getRight() + dx;
                    int t = v.getTop() + dy;
                    //下面判断移动是否超出屏幕
                    if (l < 0) {
                        l = 0;
                        r = l + v.getWidth();
                    }
                    if (t < 0) {
                        t = 0;
                        b = t + v.getHeight();
                    }
                    if (r > screenWidth) {
                        r = screenWidth;
                        l = r - v.getWidth();
                    }
                    if (b > screenHeight) {
                        b = screenHeight;
                        t = b - v.getHeight();
                    }
                    v.layout(l, t, r, b);
                    Log.e(TAG, "onTouch: " + l + "==" + t + "==" + r + "==" + b);
                    lastX = (int) event.getRawX();
                    lastY = (int) event.getRawY();
                    v.postInvalidate();
                    break;
                case MotionEvent.ACTION_UP:
                    endTime = System.currentTimeMillis();
                    toSubmit.setAlpha(1.0f);
                    //当从点击到弹起小于半秒的时候,则判断为点击,如果超过则不响应点击事件
                    if ((endTime - startTime) > 0.1 * 1000L) {
                    } else {
                        if (RegexValidateUtils.isFastClick()) {
                            startActivity(PlaceOrderActivity.class);
                        }
                    }
                    break;
            }
            return true;
        }
    };
}
